package app

import (
	"boy-go/middlewares"
	"boy-go/pkg/config"
	"boy-go/pkg/db"
	"boy-go/pkg/jwt"
	"boy-go/pkg/redis"
	"boy-go/router"
	"fmt"
	"github.com/gin-gonic/gin"
)

type App struct {
	Config *config.Config
}

func (app *App) Run() {
	r := gin.Default()
	port := fmt.Sprintf("%d", app.Config.Server.Port)
	r.Use(middlewares.ExceptionHandler())
	// 跨域
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-Token, X-User-ID")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})
	//  添加路由
	router.AddRouter(r)
	err := r.Run(":" + port)
	if err != nil {
		panic(err)
	}
}
func Run() {
	conf := config.Init()
	// 初始化数据库
	db.InitDB(conf.Database)
	// 初始化JWT
	jwt.InitJWT(conf.Token)
	// 初始化Redis
	redis.InitRedis(conf.Redis.Host, conf.Redis.Port, conf.Redis.Password, conf.Redis.Database)
	app := &App{
		Config: conf,
	}
	app.Run()
}
